<template>
  <div class="user-profile">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <div class="user-info">
            <el-avatar :size="40" :src="profileForm.avatar || '/images/avatars/default-100.png'" />
            <span class="nickname">{{ profileForm.nickname || profileForm.username }}</span>
          </div>
          <el-button type="primary" @click="editMode = !editMode" v-if="!editMode">
            编辑我的个人信息
          </el-button>
          <div v-else class="edit-actions">
            <el-button type="primary" @click="saveProfile" :loading="saving">
              保存个人信息
            </el-button>
            <el-button @click="cancelEdit">
              取消编辑
            </el-button>
          </div>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="profileForm"
        :rules="formRules"
        label-width="100px"
        :disabled="!editMode"
      >
        <!-- 头像上传区域 -->
        <div class="avatar-section">
          <el-form-item>
            <div class="avatar-upload">
              <el-avatar :size="100" :src="profileForm.avatar || '/images/avatars/default-100.png'" />
              <el-upload
                v-if="editMode"
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarUpload"
              >
                <el-button size="small" type="primary">更换头像</el-button>
              </el-upload>
            </div>
          </el-form-item>
        </div>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="profileForm.username" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="profileForm.email" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="profileForm.nickname" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="profileForm.realName" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="profileForm.phone" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item label="状态" prop="status">
              <el-input v-model="profileForm.status" disabled>
                <template #append>
                  <el-tag :type="profileForm.status === 1 ? 'success' : 'danger'" size="small">
                    {{ profileForm.status === 1 ? '正常' : '禁用' }}
                  </el-tag>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="profileForm.gender" placeholder="请选择性别">
                <el-option label="保密" :value="0" />
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker
                v-model="profileForm.birthday"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 只读信息展示 -->
        <el-divider>账号信息</el-divider>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="8" :md="8">
            <el-form-item label="账号状态">
              <el-tag :type="profileForm.status === 1 ? 'success' : 'danger'">
                {{ profileForm.status === 1 ? '正常' : '禁用' }}
              </el-tag>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="8" :md="8">
            <el-form-item label="创建时间">
              <span>{{ new Date(profileForm.createdAt).toLocaleString() }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="8" :md="8">
            <el-form-item label="更新时间">
              <span>{{ new Date(profileForm.updatedAt).toLocaleString() }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 移除原来的保存和取消按钮，现在在头部显示 -->
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onActivated } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import { authService } from '@/api'
import { productService } from '@/api'

const authStore = useAuthStore()

// 响应式数据
const editMode = ref(false)
const saving = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const profileForm = reactive({
  username: '',
  email: '',
  realName: '',
  phone: '',
  nickname: '',
  gender: 0,
  birthday: '',
  avatar: '',
  status: 1,
  createdAt: '',
  updatedAt: '',
})

// 表单验证规则
const formRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
}

// 方法
const loadProfile = () => {
  const user = authStore.user
  if (user) {
    profileForm.username = user.username || ''
    profileForm.email = user.email || ''
    profileForm.realName = user.realName || ''
    profileForm.phone = user.phone || ''
    profileForm.nickname = user.nickname || ''
    profileForm.gender = user.gender || 0
    profileForm.birthday = user.birthday || ''
    profileForm.avatar = user.avatarUrl || ''
    profileForm.status = user.status || 1
    profileForm.createdAt = user.createdAt || ''
    profileForm.updatedAt = user.updatedAt || ''
  }
}

// 每次进入页面时从后端拉取最新资料并应用到表单
const refreshProfile = async () => {
  try {
    await authStore.fetchUserProfile()
  } catch (error) {
    console.error('刷新用户信息失败:', error)
  } finally {
    loadProfile()
  }
}

const saveProfile = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    saving.value = true

    // 创建不包含状态字段的更新数据
    const updateData = { ...profileForm }
    // 移除状态字段，不允许用户修改
    if ('status' in updateData) {
      delete (updateData as any).status
    }

    const result = await authService.updateProfile(updateData)
    if (result?.data?.code === 200) {
      editMode.value = false
      ElMessage.success('个人信息更新成功')
    }
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    saving.value = false
  }
}

const cancelEdit = () => {
  editMode.value = false
  loadProfile() // 重新加载原始数据
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

const handleAvatarUpload = async (options: any) => {
  try {
    // 调用通用图片上传API
    const response = await productService.uploadImage(options.file)
    
    if (response.data.code === 200 && response.data.data) {
      // 后端UploadServiceImpl已经返回带/uploads前缀的URL
      let imageUrl = response.data.data
      
      // 确保URL格式正确：如果不以/uploads开头，则添加前缀
      if (imageUrl && !imageUrl.startsWith('/uploads/') && !imageUrl.startsWith('http')) {
        // 如果以/开头但不是/uploads，去掉/再添加/uploads
        if (imageUrl.startsWith('/')) {
          imageUrl = '/uploads' + imageUrl
        } else {
          imageUrl = '/uploads/' + imageUrl
        }
      }
      
      console.log('处理后的头像URL:', imageUrl)
      
      // 更新头像URL到表单 - 统一使用avatarUrl字段
      profileForm.avatarUrl = imageUrl
      profileForm.avatar = imageUrl // 保持显示字段同步
      
      // 调用用户信息更新API，只更新头像字段
      const updateResult = await authService.updateProfile({
        avatarUrl: imageUrl
      })
      
      if (updateResult?.data?.code === 200) {
        // 更新成功后刷新用户信息
        await authStore.fetchUserProfile()
        loadProfile()
        ElMessage.success('头像上传成功')
      } else {
        ElMessage.error('头像保存失败')
      }
    } else {
      ElMessage.error('头像上传失败')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  }
}

// 组件挂载与激活时均刷新数据（支持 keep-alive 场景）
onMounted(() => {
  refreshProfile()
})
onActivated(() => {
  refreshProfile()
})
</script>

<style scoped>
.user-profile {
  max-width: 800px;
  margin: 0 auto;
}

.profile-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.nickname {
  font-size: 18px;
  font-weight: 500;
}

.avatar-section {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.avatar-uploader {
  text-align: center;
}

.edit-actions {
  display: flex;
  gap: 10px; /* Adjust as needed */
}

@media (max-width: 768px) {
  .user-profile {
    max-width: 100%;
    padding: 0 15px;
  }
  
  .profile-card {
    margin-bottom: 15px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .edit-actions {
    flex-direction: column;
    gap: 8px;
    width: 100%;
  }
  
  .edit-actions .el-button {
    width: 100%;
  }
  
  .avatar-section {
    margin-bottom: 20px;
  }
  
  .avatar-upload {
    gap: 12px;
  }
  
  .el-form-item {
    margin-bottom: 18px;
  }
  
  .el-form-item__label {
    font-size: 14px;
    line-height: 1.4;
  }
  
  .el-input,
  .el-select,
  .el-date-picker {
    font-size: 14px;
  }
  
  .el-button {
    width: 100%;
    margin-bottom: 10px;
  }
  
  .el-divider {
    margin: 20px 0;
  }
  
  .el-row {
    margin: 0 !important;
  }
  
  .el-col {
    padding: 0 !important;
    margin-bottom: 10px;
  }
}

@media (max-width: 480px) {
  .user-profile {
    padding: 0 10px;
  }
  
  .profile-card {
    margin-bottom: 10px;
  }
  
  .card-header {
    gap: 12px;
  }
  
  .avatar-section {
    margin-bottom: 15px;
  }
  
  .el-form-item {
    margin-bottom: 15px;
  }
  
  .el-form-item__label {
    font-size: 13px;
  }
  
  .el-input,
  .el-select,
  .el-date-picker {
    font-size: 13px;
  }
}
</style>
